﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;

namespace iEN.Report
{
    public class ExportLib
    {
        public static void TransferDocToHTML(string wordPath)
        {
            string htmlPath = wordPath.Replace(".doc", ".html");

            //引用Microsoft.Office.Interop.Word
            ApplicationClass word = new ApplicationClass();
            Type wordType = word.GetType();
            Documents docs = word.Documents;

            //打開word
            Type docsType = docs.GetType();
            object fileName = wordPath;
            Document doc = (Document)docsType.InvokeMember("Open", BindingFlags.InvokeMethod, null, (object)docs, new Object[] { fileName, true, true });

            //判斷轉換的html file是否存在，存在則刪除
            if (File.Exists(htmlPath))
            {
                File.Delete(htmlPath);
            }

            //每個html file，會有對應之存放html元素的資料夾.files
            if (Directory.Exists(htmlPath.Replace(".html", ".files")))
            {
                Directory.Delete(htmlPath.Replace(".html", ".files"), true);
            }

            //轉換格式，使用word的「另存新檔」方法
            Type docType = doc.GetType();
            object saveFileName = htmlPath;
            docType.InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML });

            //退出Word
            wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null);
            word.Quit();

            //判斷轉換的word file是否存在，存在則刪除
            if (File.Exists(wordPath))
            {
                File.Delete(wordPath);
            }

            //每個html file，會有對應之存放html元素的資料夾.files，再重新刪除一次
            if (Directory.Exists(htmlPath.Replace(".html", ".files")))
            {
                Directory.Delete(htmlPath.Replace(".html", ".files"), true);
            }
        }
    }
}